/*
 * ﻿Copyright (C) 2013 NewMain Softech
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package com.newmainsoftech.eatestutil.container.glassfish;

import java.lang.reflect.Field;
import java.text.MessageFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.JDK14LoggerAdapter;

/**
 * Helper class in working around issue with SLF4J binding on Glassfish.<br />
 * 
 * @author Arata Y.
 */
public class Slf4jJulLoggerConfigurator {
	/**
	 * Get JUL logger bound to SLF4J logger provided by <code>slf4jLogger</code> argument.<br />
	 * 
	 * @param slf4jLogger
	 * @return JUL logger bound to SLF4J logger.
	 */
	public java.util.logging.Logger getBoundJulLogger( final Logger slf4jLogger) {
		Field loggerField = null; 
			try {
				loggerField = JDK14LoggerAdapter.class.getDeclaredField( "logger");
					loggerField.setAccessible( true);
			}
			catch( Exception exception) {
				String jDK14LoggerAdapterPath = "";
					try {
						jDK14LoggerAdapterPath
						= JDK14LoggerAdapter.class.getProtectionDomain()
							.getCodeSource().getLocation().getFile().replace( "%20", " ");
					}
					catch( Exception ignore) {}
				throw new RuntimeException(
						MessageFormat.format(
								"Failure in obtaining JUL logger member field defined in {0} class. " 
								+ "It could be caused by change regarding {0} class" 
								+ "{1,choice,0#.,0< what had been loaded from {2}.}",
								JDK14LoggerAdapter.class.getSimpleName(),
								jDK14LoggerAdapterPath.length(),
								jDK14LoggerAdapterPath),
						exception);
			}
		try {
			return (java.util.logging.Logger)(loggerField.get( slf4jLogger));
		}
		catch( Exception exception) {
			throw new RuntimeException(
					MessageFormat.format(
							"Failure in obtaining JUL logger object held by {0} member field of {1}.",
							loggerField,  
							slf4jLogger),
					exception);
		}
	}

	/**
	 * Check whether SLF4J logger is bound to <code>JDK14LoggerAdapter</code> adapter.<br />
	 * 
	 * @return boolean value indicating whether SLF4J logger is bound to 
	 * <code>JDK14LoggerAdapter</code> adapter.
	 */
	public boolean isBoundToJDK14LoggerAdapter() {
		Logger rootSlf4jLogger = LoggerFactory.getLogger( Logger.ROOT_LOGGER_NAME);
		return JDK14LoggerAdapter.class.isInstance( rootSlf4jLogger);
	}
}
